<?php
/**
 * Created by PhpStorm.
 * User: 73640
 * Date: 2018/10/25
 * Time: 18:15
 */

namespace App\Admin\Extensions\Form;

use Encore\Admin\Form\Field;
class Tag extends  Field
{
    protected $view = 'admin.tag';
    protected $value = [];
    protected static $css = [


    ];

    protected static $js = [
        "/js/tag.js"
    ];

    /**
     * {@inheritdoc}
     */
    public function fill($data)
    {
        $this->value = array_get($data, $this->column);

        if (is_string($this->value)) {
            $this->value = explode(',', $this->value);
        }

        $this->value = array_filter((array) $this->value, 'strlen');
    }

    /**
     * {@inheritdoc}
     */
    public function prepare($value)
    {
        if (is_array($value) && !Arr::isAssoc($value)) {
            $value = implode(',', array_filter($value, 'strlen'));
        }

        return $value;
    }

    /**
     * Get or set value for this field.
     *
     * @param mixed $value
     *
     * @return $this|array|mixed
     */
    public function value($value = null)
    {
        if (is_null($value)) {
            return empty($this->value) ? ($this->getDefault() ?? []) : $this->value;
        }

        $this->value = (array) $value;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        $this->script = "$(\"{$this->getElementClassSelector()}\").select2({
            tags: true,
            tokenSeparators: [',']
        });";

        return parent::render()->with([
            'options' => array_unique(array_merge($this->value, $this->options)),
        ]);
    }
}